<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="searchForm.content" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddNews">发布资讯</el-button>
    </div>

    <!-- 资讯表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="id" label="资讯ID" width="80"/>
      <el-table-column prop="title" label="标题" show-overflow-tooltip/>
      <el-table-column prop="content" label="内容" show-overflow-tooltip/>
      <el-table-column prop="createTime" label="发布时间" width="180"/>
      <el-table-column prop="updateTime" label="更新时间" width="180"/>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditNews(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteNews(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑资讯对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
      <el-form :model="currentForm" :rules="rules" ref="newsFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="currentForm.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
              v-model="currentForm.content"
              type="textarea"
              :rows="10"
              placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {newsDeleteOne, newsInsertOne, newsSelectPage, newsUpdateOne} from "@/api/news.js";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const refreshKey = ref(0);

// 搜索条件
const searchForm = reactive({
  title: '',
  content: '',
});

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  id: 0,
  title: '',
  content: '',
  createTime: '',
  updateTime: '',
});
const newsFormRef = ref(null);

// 验证规则
const rules = {
  title: [
    {required: true, message: '标题不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '标题长度在2到50个字符之间', trigger: 'blur'}
  ],
  content: [
    {required: true, message: '内容不能为空', trigger: 'blur'},
    {min: 10, message: '内容长度不能少于10个字符', trigger: 'blur'}
  ],
};

// 获取资讯列表
const fetchNews = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      title: searchForm.title,
      content: searchForm.content,
    };
    if (params.title === '') {
      delete params.title;
    }
    if (params.content === '') {
      delete params.content;
    }
    const response = await newsSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取资讯列表失败');
  }
};

// 新增资讯
const handleAddNews = () => {
  dialogTitle.value = '发布资讯';
  dialogVisible.value = true;
  resetForm();
};

// 编辑资讯
const handleEditNews = (row) => {
  dialogTitle.value = '编辑资讯';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
};

// 删除资讯
const handleDeleteNews = (newsId) => {
  ElMessageBox.confirm('确认删除该资讯?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await newsDeleteOne(newsId);
      ElMessage.success('删除成功');
      await fetchNews();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存资讯（新增/编辑）
const handleSubmit = () => {
  newsFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.id) {
          // 编辑
          await newsUpdateOne(currentForm);
        } else {
          // 新增
          await newsInsertOne(currentForm)
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchNews();
      } catch (error) {
        ElMessage.error('保存失败');
      } finally {
        resetForm();
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchNews();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchNews();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchNews();
};

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1;
  Object.assign(searchForm, {
    title: '',
    content: '',
  });
  fetchNews();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    id: 0,
    title: '',
    content: '',
    createTime: '',
    updateTime: '',
  });
  newsFormRef.value?.clearValidate();
};

// 初始化数据
onMounted(() => {
  fetchNews();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.w-e-text-container) {
  min-height: 400px !important;
}
</style> 